package com.prd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.prd.config.IdGeneratorSnowflake;
import com.prd.config.LoginInterceptor;
import com.prd.dto.WorkContactFormDTO;
import com.prd.dto.WorkInputRecordDTO;
import com.prd.dto.WorkPointRecordDTO;
import com.prd.dto.WorkTimeNodeRecordDTO;
import com.prd.enums.WorkContactFormStatusEnum;
import com.prd.enums.WorkInputTpyeEnum;
import com.prd.enums.WorkMoudleTypeEnum;
import com.prd.enums.WorkPointTypeEnum;
import com.prd.mapper.WorkInputRecordMapper;
import com.prd.mapper.WorkPointRecordMapper;
import com.prd.mapper.WorkTimeNodeRecordMapper;
import com.prd.model.*;
import com.prd.mapper.WorkContactFormMapper;
import com.prd.service.WorkContactFormService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.prd.service.WorkInputRecordService;
import com.prd.util.CommonUtil;
import com.prd.util.JsonData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 工作联络单数据表 服务实现类
 * </p>
 *
 * @author lizhaoyi
 * @since 2023-11-06
 */
@Service
@Slf4j
public class WorkContactFormServiceImpl extends ServiceImpl<WorkContactFormMapper, WorkContactFormDO> implements WorkContactFormService {

    @Autowired
    private IdGeneratorSnowflake idGeneratorSnowflake;

    private WorkContactFormMapper workContactFormMapper;
    private WorkPointRecordMapper workPointRecordMapper;
    private WorkInputRecordMapper workInputRecordMapper;
    private WorkTimeNodeRecordMapper workTimeNodeRecordMapper;
    private WorkInputRecordService workInputRecordService;

    public WorkContactFormServiceImpl(WorkContactFormMapper workContactFormMapper, WorkPointRecordMapper workPointRecordMapper, WorkInputRecordMapper workInputRecordMapper, WorkTimeNodeRecordMapper workTimeNodeRecordMapper, WorkInputRecordService workInputRecordService) {
        this.workContactFormMapper = workContactFormMapper;
        this.workPointRecordMapper = workPointRecordMapper;
        this.workInputRecordMapper = workInputRecordMapper;
        this.workTimeNodeRecordMapper = workTimeNodeRecordMapper;
        this.workInputRecordService = workInputRecordService;
    }



    /**
     * 新建工作联络单
     * @param workContactFormDTO
     * @return
     */
    @Override
    public JsonData creatWorkOrder(WorkContactFormDTO workContactFormDTO) {

        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        WorkContactFormDO workContactFormDO = CommonUtil.dtoTransfer(workContactFormDTO, WorkContactFormDO.class);
        Long formId = idGeneratorSnowflake.snowflakeId();
        if (workContactFormDTO.getWorkInputRecordDTO() != null) {
            //新增工作单描述
            WorkPointRecordDTO workPointRecordDTO = workContactFormDTO.getWorkPointRecordDTO();
            // TODO 相关文件上传oss文件夹，申请oss服务后再上传
            workPointRecordDTO.setWorkContactFormId(formId);
            workPointRecordDTO.setModule(WorkMoudleTypeEnum.WORK_CONTACT_FORM.getMessage());
            workPointRecordDTO.setType(WorkPointTypeEnum.WORK_DESCRIBE.getCode());
            workPointRecordDTO.setTypeName(WorkPointTypeEnum.WORK_DESCRIBE.getMessage());
            int insert = workPointRecordMapper.insert(CommonUtil.dtoTransfer(workPointRecordDTO, WorkPointRecordDO.class));
            if (insert < 0) {
                JsonData.buildError("新增工作单描述失败");
            }
        }
        if (workContactFormDTO.getWorkTimeNodeRecordDTO() != null) {
            //新增时间节点
            WorkTimeNodeRecordDO workTimeNodeRecordDO = CommonUtil.dtoTransfer(workContactFormDTO.getWorkTimeNodeRecordDTO(), WorkTimeNodeRecordDO.class);
            workTimeNodeRecordDO.setWorkOrderId(formId);
            workTimeNodeRecordDO.setModule(WorkMoudleTypeEnum.WORK_ORDER.getMessage());
            workTimeNodeRecordMapper.insert(workTimeNodeRecordDO);
        }
        workContactFormDO.setId(formId);
        workContactFormDO.setCreatedWorkFormBy(loginUser.getName());
        workContactFormDO.setCreatedWorkFormId(loginUser.getId());
        workContactFormDO.setCreatedById(loginUser.getId());
        workContactFormDO.setCreatedBy(loginUser.getName());
        workContactFormDO.setCreatedTime(LocalDateTime.now());
        int insert = workContactFormMapper.insert(workContactFormDO);
        //TODO 发送短信接收人
        return insert > 0 ? JsonData.buildSuccess() : JsonData.buildError("新建工作联络单异常");

    }

    /**
     * 查看工作联络单详情
     * @param id
     * @param userId
     * @return
     */
    @Override
    public JsonData getDetail(Long id, String userId) {

        WorkContactFormDO workContactFormDO = checkFormExistOrNot(id);

        WorkContactFormDTO workContactFormDTO = CommonUtil.dtoTransfer(workContactFormDO, WorkContactFormDTO.class);
        //获取要点描述
        List<WorkPointRecordDO> workPointRecordDOList = workPointRecordMapper.selectList(new LambdaQueryWrapper<WorkPointRecordDO>().eq(WorkPointRecordDO::getWorkContactFormId, id));
        workContactFormDTO.setWorkPointRecordDTOList(CommonUtil.dtoListTransfer(workPointRecordDOList,WorkPointRecordDTO.class));
        //获取决算记录
        List<WorkInputRecordDO> inputRecordDOList = workInputRecordMapper.selectList(new LambdaQueryWrapper<WorkInputRecordDO>().eq(WorkInputRecordDO::getWorkContactFormId, id));
        workContactFormDTO.setWorkInputRecordDTOList(CommonUtil.dtoListTransfer(inputRecordDOList, WorkInputRecordDTO.class));
        //获取时间节点记录
        List<WorkTimeNodeRecordDO> workTimeNodeRecordDOList = workTimeNodeRecordMapper.selectList(new LambdaQueryWrapper<WorkTimeNodeRecordDO>().eq(WorkTimeNodeRecordDO::getWorkContactFormId, id));
        workContactFormDTO.setWorkTimeNodeRecordDTOList(CommonUtil.dtoListTransfer(workTimeNodeRecordDOList, WorkTimeNodeRecordDTO.class));
        return JsonData.buildSuccess(workContactFormDTO);
    }

    /**
     * 确定收到
     * @param id
     * @return
     */
    @Override
    public JsonData confirmReceipt(Long id) {

        WorkContactFormDO workContactFormDO = checkFormExistOrNot(id);
        workContactFormDO.setFormStatus(WorkContactFormStatusEnum.RECEIVED.getCode());
        int count = workContactFormMapper.updateById(workContactFormDO);

        return count > 0 ? JsonData.buildSuccess() : JsonData.buildError("确定收到操作异常");
    }

    /**
     * 办结回复
     * @param workContactFormDTO
     * @return
     */
    @Override
    public JsonData completedResponse(WorkContactFormDTO workContactFormDTO) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        if (workContactFormDTO.getWorkPointRecordDTO() == null) {
            JsonData.buildError("办结回复相关数据不能为空");
        }
        WorkPointRecordDO workPointRecordDO = CommonUtil.dtoTransfer(workContactFormDTO.getWorkPointRecordDTO(), WorkPointRecordDO.class);

        workPointRecordDO.setModule(WorkMoudleTypeEnum.WORK_CONTACT_FORM.getMessage());
        workPointRecordDO.setCreatedBy(loginUser.getName());
        workPointRecordDO.setCreatedById(loginUser.getId());
        workPointRecordDO.setCreatedTime(LocalDateTime.now());
        workPointRecordDO.setType(WorkPointTypeEnum.COMPLETED_RESPONSE.getCode());
        workPointRecordDO.setTypeName(WorkPointTypeEnum.COMPLETED_RESPONSE.getMessage());

        int count = workPointRecordMapper.insert(workPointRecordDO);

        return count > 0 ? JsonData.buildSuccess() : JsonData.buildError("办结回复操作异常");
    }

    /**
     * 安排执行人/由我执行
     * @param id
     * @param userId
     * @return
     */
    @Override
    public JsonData setExecutor(Long id, Long userId) {

        WorkContactFormDO workContactFormDO = checkFormExistOrNot(id);
        workContactFormDO.setExecutor(userId.toString());
        workContactFormDO.setExecutorId(userId);

        int count = workContactFormMapper.updateById(workContactFormDO);

        return count > 0 ? JsonData.buildSuccess() : JsonData.buildError("安排执行人/由我执行操作异常");

    }

    /**
     * 执行汇报
     * @param workContactFormDTO
     * @return
     */
    @Override
    public JsonData executionReport(WorkContactFormDTO workContactFormDTO) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        if (workContactFormDTO.getWorkPointRecordDTO() == null) {
            JsonData.buildError("补充执行汇报传参为空");
        }

        WorkPointRecordDO workPointRecordDO = CommonUtil.dtoTransfer(workContactFormDTO.getWorkPointRecordDTO(), WorkPointRecordDO.class);
        workPointRecordDO.setWorkContactFormId(workPointRecordDO.getId());
        workPointRecordDO.setCreatedBy(loginUser.getName());
        workPointRecordDO.setCreatedById(loginUser.getId());
        workPointRecordDO.setCreatedTime(LocalDateTime.now());
        workPointRecordDO.setModule(WorkMoudleTypeEnum.WORK_CONTACT_FORM.getMessage());
        workPointRecordDO.setType(WorkPointTypeEnum.EXECUTION_REPORT.getCode());
        workPointRecordDO.setTypeName(WorkPointTypeEnum.EXECUTION_REPORT.getMessage());

        int count = workPointRecordMapper.insert(workPointRecordDO);

        return count > 0 ? JsonData.buildSuccess() : JsonData.buildError("补充执行汇报操作异常");
    }

    /**
     * 决算
     * @param workContactFormDTO
     * @return
     */
    @Override
    public JsonData finalAccount(WorkContactFormDTO workContactFormDTO) {
        if (workContactFormDTO.getWorkInputRecordDTOList() == null) {
            return JsonData.buildError("投入记录为空");
        }

        List<WorkInputRecordDO> workInputRecordDOS = CommonUtil.dtoListTransfer(workContactFormDTO.getWorkInputRecordDTOList(), WorkInputRecordDO.class);
        if (workInputRecordService.saveBatch(workInputRecordDOS)) {
            return JsonData.buildSuccess();
        }else {
            return JsonData.buildError("决算操作异常");
        }
    }

    /**
     * 安排督导人员/由我督导
     * @param id
     * @param userId
     * @return
     */
    @Override
    public JsonData setWatcher(Long id, Long userId) {
        WorkContactFormDO workContactFormDO = checkFormExistOrNot(id);
        workContactFormDO.setSupervisor(userId.toString());
        workContactFormDO.setSupervisorId(userId);

        int count = workContactFormMapper.updateById(workContactFormDO);

        return count > 0 ? JsonData.buildSuccess() : JsonData.buildError("安排督导人员操作异常");
    }

    /**
     * 未达标/不合格
     * @param workContactFormDTO
     * @return
     */
    @Override
    public JsonData notStandard(WorkContactFormDTO workContactFormDTO) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        if (workContactFormDTO.getWorkPointRecordDTO() == null) {
            JsonData.buildError("未达标/不合格传参为空");
        }
        WorkPointRecordDO workPointRecordDO = CommonUtil.dtoTransfer(workContactFormDTO.getWorkPointRecordDTO(), WorkPointRecordDO.class);
        workPointRecordDO.setWorkContactFormId(workContactFormDTO.getId());
        workPointRecordDO.setCreatedBy(loginUser.getName());
        workPointRecordDO.setCreatedById(loginUser.getId());
        workPointRecordDO.setCreatedTime(LocalDateTime.now());
        workPointRecordDO.setType(WorkPointTypeEnum.NOT_STANDARD.getCode());
        workPointRecordDO.setTypeName(WorkPointTypeEnum.NOT_STANDARD.getMessage());
        workPointRecordDO.setModule(WorkMoudleTypeEnum.WORK_CONTACT_FORM.getMessage());

        int count = workPointRecordMapper.insert(workPointRecordDO);

        return count > 0 ? JsonData.buildSuccess() : JsonData.buildError("未达标/不合格操作异常");
    }

    /**
     * 达标/合格
     * @param workContactFormDTO
     * @return
     */
    @Override
    public JsonData standard(WorkContactFormDTO workContactFormDTO) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        if (workContactFormDTO.getWorkPointRecordDTO() == null) {
            JsonData.buildError("达标/合格传参为空");
        }
        WorkPointRecordDO workPointRecordDO = CommonUtil.dtoTransfer(workContactFormDTO.getWorkPointRecordDTO(), WorkPointRecordDO.class);
        workPointRecordDO.setWorkContactFormId(workContactFormDTO.getId());
        workPointRecordDO.setCreatedBy(loginUser.getName());
        workPointRecordDO.setCreatedById(loginUser.getId());
        workPointRecordDO.setCreatedTime(LocalDateTime.now());
        workPointRecordDO.setType(WorkPointTypeEnum.STANDARD.getCode());
        workPointRecordDO.setTypeName(WorkPointTypeEnum.STANDARD.getMessage());
        workPointRecordDO.setModule(WorkMoudleTypeEnum.WORK_CONTACT_FORM.getMessage());

        int count = workPointRecordMapper.insert(workPointRecordDO);

        return count > 0 ? JsonData.buildSuccess() : JsonData.buildError("达标/合格操作异常");
    }

    /**
     * 预算执行误差报告
     * @param workContactFormDTO
     * @return
     */
    @Override
    public JsonData executionErrorReport(WorkContactFormDTO workContactFormDTO) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        if (workContactFormDTO.getWorkPointRecordDTO() == null) {
            JsonData.buildError("预算执行误差报告传参为空");
        }
        WorkPointRecordDO workPointRecordDO = CommonUtil.dtoTransfer(workContactFormDTO.getWorkPointRecordDTO(), WorkPointRecordDO.class);
        workPointRecordDO.setWorkContactFormId(workContactFormDTO.getId());
        workPointRecordDO.setCreatedBy(loginUser.getName());
        workPointRecordDO.setCreatedById(loginUser.getId());
        workPointRecordDO.setCreatedTime(LocalDateTime.now());
        workPointRecordDO.setType(WorkPointTypeEnum.EXECUTION_ERROR_REPORT.getCode());
        workPointRecordDO.setTypeName(WorkPointTypeEnum.EXECUTION_ERROR_REPORT.getMessage());
        workPointRecordDO.setModule(WorkMoudleTypeEnum.WORK_CONTACT_FORM.getMessage());

        int count = workPointRecordMapper.insert(workPointRecordDO);

        return count > 0 ? JsonData.buildSuccess() : JsonData.buildError("预算执行误差报告操作异常");
    }

    /**
     * 预决算意见
     * @param workContactFormDTO
     * @return
     */
    @Override
    public JsonData budgetOpinion(WorkContactFormDTO workContactFormDTO) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        if (workContactFormDTO.getWorkPointRecordDTO() == null) {
            JsonData.buildError("预决算意见传参为空");
        }
        WorkPointRecordDO workPointRecordDO = CommonUtil.dtoTransfer(workContactFormDTO.getWorkPointRecordDTO(), WorkPointRecordDO.class);
        workPointRecordDO.setWorkContactFormId(workContactFormDTO.getId());
        workPointRecordDO.setCreatedBy(loginUser.getName());
        workPointRecordDO.setCreatedById(loginUser.getId());
        workPointRecordDO.setCreatedTime(LocalDateTime.now());
        workPointRecordDO.setType(WorkPointTypeEnum.BUDGET_OPINION.getCode());
        workPointRecordDO.setTypeName(WorkPointTypeEnum.BUDGET_OPINION.getMessage());
        workPointRecordDO.setModule(WorkMoudleTypeEnum.WORK_CONTACT_FORM.getMessage());

        int count = workPointRecordMapper.insert(workPointRecordDO);

        return count > 0 ? JsonData.buildSuccess() : JsonData.buildError("预决算意见操作异常");
    }

    /**
     * 预完成
     * @param id
     * @return
     */
    @Override
    public JsonData preComplete(Long id) {
        WorkContactFormDO workContactFormDO = checkFormExistOrNot(id);
        workContactFormDO.setFormStatus(WorkContactFormStatusEnum.PRE_FINISHED.getCode());
        int count = workContactFormMapper.updateById(workContactFormDO);

        return count > 0 ? JsonData.buildSuccess() : JsonData.buildError("预完成操作异常");
    }

    /**
     * 完成
     * @param id
     * @return
     */
    @Override
    public JsonData complete(Long id) {
        WorkContactFormDO workContactFormDO = checkFormExistOrNot(id);
        workContactFormDO.setFormStatus(WorkContactFormStatusEnum.FINISHED.getCode());
        int count = workContactFormMapper.updateById(workContactFormDO);

        return count > 0 ? JsonData.buildSuccess() : JsonData.buildError("完成操作异常");
    }

    /**
     * 取消联络单
     * @param id
     * @return
     */
    @Override
    public JsonData cancelContactForm(Long id) {
        WorkContactFormDO workContactFormDO = checkFormExistOrNot(id);
        workContactFormDO.setFormStatus(WorkContactFormStatusEnum.CANCELED.getCode());
        int count = workContactFormMapper.updateById(workContactFormDO);

        return count > 0 ? JsonData.buildSuccess() : JsonData.buildError("取消联络单操作异常");
    }

    /**
     * 增加抄送人
     * @param id
     * @param userId
     * @return
     */
    @Override
    public JsonData addCC(Long id, String userId) {

        WorkContactFormDO workContactFormDO = checkFormExistOrNot(id);
        if (workContactFormDO.getCcTo() != null) {
            List<String> ccList = Arrays.asList(workContactFormDO.getCcTo().split(","));
            ccList.add(String.valueOf(userId));
            String ccString = ccList.toString();
            workContactFormDO.setCcTo(ccString);

        }else {
            workContactFormDO.setCcTo(String.valueOf(userId));
        }

        int count = workContactFormMapper.updateById(workContactFormDO);

        return count > 0 ? JsonData.buildSuccess() : JsonData.buildError("增加抄送人操作异常");
    }

    /**
     * 分页查询工作联络单
     * @param page
     * @param size
     * @return
     */
    @Override
    public JsonData selectPage(int page, int size) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        Page<WorkContactFormDO> pageInfo = new Page<>();
        Page<WorkContactFormDO> workContactFormDOPage = workContactFormMapper.selectPage(pageInfo, new LambdaQueryWrapper<WorkContactFormDO>()
                .eq(WorkContactFormDO::getCreatedWorkFormId, loginUser.getId()).orderByDesc(WorkContactFormDO::getCreatedTime));
        Map<String,Object> pageMap = new HashMap<>(3);
        pageMap.put("total_record",workContactFormDOPage.getTotal());
        pageMap.put("total_page",workContactFormDOPage.getPages());
        pageMap.put("current_data",CommonUtil.dtoListTransfer(workContactFormDOPage.getRecords(), WorkContactFormDTO.class));

        return JsonData.buildSuccess(pageMap);
    }

    private WorkContactFormDO checkFormExistOrNot(Long id) {
        LambdaQueryWrapper<WorkContactFormDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WorkContactFormDO::getId,id).eq(WorkContactFormDO::getCreatedWorkFormId,id);
        WorkContactFormDO workContactFormDO = workContactFormMapper.selectOne(wrapper);
        if (workContactFormDO == null) {
            JsonData.buildError("数据不存在");
        }
        return workContactFormDO;
    }
}
